//
//  LoginModel.m
//  RainbowFM
//
//  Created by chenli on 14/12/17.
//  Copyright (c) 2014年 RB. All rights reserved.
//

#import "LoginModel.h"
#import "LoginAPI.h"
#import "UserModel.h"

@implementation LoginModel

+(instancetype)sharedModel
{
    static LoginModel *loginModel = nil;
    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        loginModel = [[LoginModel alloc] init];
    });
    
    return loginModel;
    
}


-(void)fetchSecurityCodeWithPhoneNum:(NSString *)phoneNum result:(void (^)(BOOL, NSString *))res{
   __block LoginAPI *loginAPI = [[LoginAPI alloc] init];
    [loginAPI fetchSecurityCodeWithPhoneNum:phoneNum result:^(BOOL success, NSString *msg) {
        res(success,msg);
        loginAPI = nil;
    }];
}

-(void)verifyPhoneNumAndCode:(NSString *)code phoneNum:(NSString *)phoneNum result:(void (^)(BOOL ,NSString *, NSString *))res{
    __block LoginAPI *loginAPI = [[LoginAPI alloc] init];
    [loginAPI verifyPhoneNumAndCode:code phoneNum:phoneNum result:^(NSString *code, NSString *msg) {
        if (code != nil) {
            res(YES,code,msg);
        }else{
            res(NO,code,msg);
        }
        loginAPI = nil;
    }];
}


-(void)registerWithPhoneNum:(NSString *)phoneNum smsCode:(NSString *)code password:(NSString *)pwd verifyPassword:(NSString *)verifyPwd result:(void (^)(BOOL,NSString *))res{
    //这里还需要添加电话号码验证，密码和确认密码的验证
    
    __block LoginAPI *loginAPI = [[LoginAPI alloc] init];
    [loginAPI registerWithPhoneNum:phoneNum smsCode:code password:pwd result:^(BOOL success,NSString *msg) {
        res(success,msg);
    }];
    
}

-(void)loginWithPhoneNum:(NSString *)phoneNum password:(NSString *)pwd result:(void (^)(BOOL, NSString *))res{
    
    __block LoginAPI *loginAPI = [[LoginAPI alloc] init];
    [loginAPI loginWithPhoneNum:phoneNum password:pwd result:^(NSString *token, NSString *userID, NSString *msg) {
        if (token != nil && userID != nil) {
            self.token = token;
            self.userID = userID;
            [[UserModel sharedModel] fetchUserProfile:^(BOOL success) {
                res(success,msg);
            }];
            
//            [[NSNotificationCenter defaultCenter] postNotification:kRFMNotificationLoginSucceed];
            
            
        }else{
            res(NO,msg);
        }
    }];
}

@end
